// pages/addimage/addimage.js
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    type: null,
    imgs: [], //照片路径
    imgBase64: "", //base64图片
    isshow: "true",
    id: "",
    naa: "", //添加图片项目名称
    imgurlpath: app.globalData.imgURL + "/template/",
    imagepathurl: "https://wx.wc5818.com/images/template/tu.png",
    countsize: 0,
    imgsbl: 0, //是否显示
    imgslist: [],
    pics: [],
    tupian: "",
    tutu: [], //图的列表,
    token: null
  },

  //删除照片功能
  deleteImage: function(e) {
    var that = this;

    var tempFilePaths = that.data.pics; //获取当前图片
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    let selectedObj = tempFilePaths[index];

    wx.showModal({
      title: "提示",
      content: "确定要删除此图片吗？",
      success: function(res) {
        if (res.confirm) {
          console.log("点击确定了");

          if (selectedObj.id == null) {
            tempFilePaths.splice(index, 1);
            that.setData({
              pics: tempFilePaths
            });
            return;
          }

          wx.request({
            url:
              app.globalData.serviceUrl +
              "/wcImageDetail/deleteById?id=" +
              selectedObj.id,
            method: "DELETE",
            success: res => {
              if (res.data.success) {
                wx.showToast({
                  title: "操作成功",
                  icon: "none"
                });

                tempFilePaths.splice(index, 1);
                that.setData({
                  pics: tempFilePaths
                });
              } else {
                wx.showToast({
                  title: "操作失败",
                  icon: "none"
                });
              }
            }
          });
        }
      }
    });
  },

  //预览照片
  yulan: function(e) {
    var that = this;
    
    var tempFilePaths = that.data.pics; //获取当前图片
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标

    wx.previewImage({
      urls: [tempFilePaths[index].url]
    });
  },

  /**
   * 图片上传七牛云
   */
  uploadQiniu(tempFilePaths) {
    let token = this.data.token;
    var that = this;

    let tmp = [];
    tempFilePaths.forEach(element => {
      wx.uploadFile({
        url: app.globalData.serviceUrl + "/qiniu/upload",
        name: "file",
        filePath: element,
        header: {
          "Content-Type": "multipart/form-data"
        },
        formData: {
          token: token
        },
        success: function(res) {
          let data = JSON.parse(res.data);
          if (data.success) {
            tmp = that.data.pics;
            tmp.push({ url: data.downloadPath });
            that.setData({
              pics: tmp
            });
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    });
  },

  // 添加照片功能
  paizhao: function(e) {
    var that = this;

    wx.chooseImage({
      count: that.data.countsize,
      sizeType: ["original", "compressed"], //可选择原图或压缩后的图片
      sourceType: ["album", "camera"], //可选择性开放访问相册、相机
      success(res) {
        that.uploadQiniu(res.tempFilePaths);
      }
    });
  },

  // 提交保存数据的事件
  submit: function() {
    var that = this;

    if (that.data.countsize != that.data.pics.length) {
      wx.showToast({
        title: "请上传：" + that.data.countsize + "张照片",
        icon: "none"
      });
      return;
    }

    let inputData = [];
    that.data.pics.forEach(elemet => {
      let obj = {};
      obj.id = elemet.id;
      obj.path = elemet.url;
      obj.imgId = that.data.imgId;
      obj.typeId = that.data.typeId;

      inputData.push(obj);
    });

    wx.request({
      url: app.globalData.serviceUrl + "/wcImageDetail/createNew",
      method: "POST",
      data: inputData,
      success: res => {
        if (res.data.success) {
          wx.showToast({
            title: '操作成功',
            icon: "none",
          })

        } else {
          wx.showToast({
            title: '操作成功',
            icon: "none",
          });
        }

        wx.navigateBack({
          delta: 1
        });

        // wx.showModal({
        //   title: "提示",
        //   content: "操作完成是否返回？",
        //   showCancel: true, //是否显示取消按钮
        //   cancelText: "否", //默认是“取消”
        //   confirmText: "是", //默认是“确定”
        //   success: function(res) {
        //     if (res.cancel) {
        //       //点击取消,默认隐藏弹框
        //     } else {
        //       //点击确定
        //       wx.navigateBack({
        //         delta: 1
        //       });
        //     }
        //   },
        //   fail: function(res) {}, //接口调用失败的回调函数
        //   complete: function(res) {} //接口调用结束的回调函数（调用成功、失败都会执行）
        // });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;

    // 七牛上传凭证
    wx.request({
      url: app.globalData.serviceUrl + "/wcComOrder/getToken",
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "content-type": "application/json" // 默认值
      },
      success: res => {
        that.setData({
          token: res.data.uptoken
        });
      }
    });

    // 上传长度限制
    if (options.len) {
      this.setData({
        countsize: options.len,
        naa: options.naa
      });
    }

    // 保存类型
    if (options.typeId) {
      that.setData({
        typeId: options.typeId
      });
    }

    if (options.imgId) {
      that.setData({
        imgId: options.imgId
      });
    }

    wx.request({
      url: app.globalData.serviceUrl + "/wcImageDetail/queryByImgId",
      method: "GET",
      data: {
        imgId: that.data.imgId,
        typeId: that.data.typeId
      },
      success: res => {
        if (res.data.success) {
          let tmp = [];
          res.data.data.forEach(element => {
            let obj = {};
            obj.id = element.id;
            obj.url = element.path;

            tmp.push(obj);
          });

          that.setData({
            pics: tmp
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
});
